﻿using Autofac;
using Ewell.BizComponent.Service.IServer;
using Ewell.BizComponent.Service.Model.Request;
using Ewell.BizComponent.Service.Server;
using Ewell.BizComponent.UI.Charge.ViewModel;
using Ewell.BizComponent.UI.Core.Model;
using Ewell.BizComponent.UI.Core.VievModel;
using Ewell.Interface.Common.Model.Common;
using Ewell.Interface.Common.Model.GateWay.Dto.Dict;
using Ewell.Interface.Common.Model.GateWay.GateWayUriInfo;
using Ewell.Interface.Common.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Ewell.BizComponent.UI.Charge.Views
{
    /// <summary>
    /// CashierView.xaml 的交互逻辑
    /// </summary>
    public partial class CashierView : UserControl
    {
        public static readonly DependencyProperty CashierVmProperty = DependencyProperty
            .Register("cashierVm", typeof(CashierVm), typeof(CashierView),
            new FrameworkPropertyMetadata(new CashierVm()));
        public CashierVm cashierVm {
            get
            {
                if (this.DataContext?.GetType() != typeof(CashierVm))
                    return (CashierVm)GetValue(CashierVmProperty);
                else
                    return this.DataContext as CashierVm;
            }
            set { SetValue(CashierVmProperty, value); }
        }

        public IPaymentServer paymentServer { get; set; } = Global.Container.Resolve<IPaymentServer>();
        public CashierView()
        {
            InitializeComponent();
            this.DataContext = this.cashierVm;
        }

        private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (e.Text == ".")
            {
                int dotIndex = (sender as TextBox).Text.IndexOf('.');
                if (dotIndex >= 0)
                {
                    (sender as TextBox).CaretIndex = dotIndex + 1;
                    e.Handled = true;
                }
            }
        }
        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if ((sender as TextBox).Tag == null)
            {
                e.Handled = true;
                return;
            }
            if (string.IsNullOrWhiteSpace((sender as TextBox).Text)) (sender as TextBox).Text = "0";
            decimal? amt = this.cashierVm.payWayList.Where(f => f.no != (sender as TextBox).Tag.ToString() && f.amount > 0)?.Sum(f => f.amount);
            decimal.TryParse((sender as TextBox).Text, out decimal value);
            if (value > this.cashierVm.chargingInfo.recAmount - amt)//最大输入金额不能超过应收金额-已输入得金额
                (sender as TextBox).Text = (this.cashierVm.chargingInfo.recAmount - amt)?.ToString();
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            foreach (PayWayVm item in e.RemovedItems)
            {
                item.amount = 0;
            }
            //重新计算金额
            ((sender as ComboBox).SelectedItem as PayWayVm).amount = (this.cashierVm.chargingInfo.recAmount ?? 0) - (this.cashierVm.prestorePayWay?.amount ?? 0);
        }
        /// <summary>
        /// 初始化
        /// </summary>
        public void Init()
        {
            #region 支付方式
            List<PayWayVm> payWayList = new List<PayWayVm>();
            DictPayWayDubboService dictPayWayDubboService = new DictPayWayDubboService();
            PayWayQueryRequest payWayQueryRequest = new PayWayQueryRequest()
            {
                enabledFlag = "1",
                athenaMenuId = LoginInfo.menuId,
                patientTypeNo = this.cashierVm.selectedPatientType?.no,
            };
            var gateWayPayWay = dictPayWayDubboService.queryPayWayListByExample.Post<List<PayWayResponse>>(payWayQueryRequest).CheckState("诊间挂号");
            if (gateWayPayWay.@object == null || gateWayPayWay.@object?.Count <= 0) throw new SpeedException("诊间挂号", "未查询到支付方式!请检查系统设置!");
            foreach (var item in gateWayPayWay.@object)
            {
                PayWayVm payWay = item.CopyProperties<PayWayVm>();
                payWay.isDefault = "1".Equals(item.defaultFlag);
                if (payWay.interfaceId.HasValue)
                {
                    if (!string.IsNullOrWhiteSpace(this.cashierVm.patientVm.patientId))
                    {
                        //查询账户余额
                        var queryBalanceResp = paymentServer.QueryBalance(payWay.interfaceId.Value, new QueryBalanceReq() { accountOwnerNo = this.cashierVm.patientVm.patientId });
                        payWay.balance = queryBalanceResp.accountBalance;
                    }
                }
                payWay.balance = payWay.balance ?? 0;
                payWayList.Add(payWay);
            }
            this.cashierVm.payWayList = payWayList;
            #endregion

            this.cashierVm.prestorePayWay = this.cashierVm.payWayList.FirstOrDefault(f => f.no == "HIS001");
            this.cashierVm.otherPayWayList = this.cashierVm.payWayList.Where(f => f.no != "HIS001").ToList();
            cashierVm.payWayList?.ForEach(e =>
            {
                e.payAmt = 0;
                e.paySuccess = null;
                e.payErrorMsg = string.Empty;
            });
            //存在账户默认账户支付
            if (cashierVm.prestorePayWay != null)
            {
                //余额充足全部支付
                if (cashierVm.prestorePayWay.balance >= cashierVm.chargingInfo.recAmount)
                    cashierVm.prestorePayWay.amount = cashierVm.chargingInfo.recAmount.Value;
                else//余额不足剩余的填到默认或者第一个支付方式
                {
                    cashierVm.prestorePayWay.amount = cashierVm.prestorePayWay.balance ?? 0;
                    PayWayVm payWay = cashierVm.otherPayWayList?.FirstOrDefault(f => f.isDefault);
                    if (payWay != null) payWay.amount = cashierVm.chargingInfo.recAmount.Value - cashierVm.prestorePayWay.amount;
                    else
                    {
                        payWay = cashierVm.otherPayWayList?.FirstOrDefault();
                        payWay.amount = cashierVm.chargingInfo.recAmount.Value - cashierVm.prestorePayWay.amount;
                    }
                }
            }
            else//不存在账户按照设置的默认支付
            {
                PayWayVm payWay = cashierVm.otherPayWayList?.FirstOrDefault(f => f.isDefault);
                if (payWay == null) payWay = cashierVm.otherPayWayList?.FirstOrDefault();
                if (payWay != null) payWay.amount = cashierVm.chargingInfo.recAmount.Value;
            }
            #region 单支付方式下拉框默认选中设置的 没有设置的默认第一个
            foreach (PayWayVm item in this.cashierVm.otherPayWayList)
            {
                if (item.isDefault)
                    this.cashierVm.selectPayWay = item;
            }
            if (this.cashierVm.selectPayWay == null)
                this.cashierVm.selectPayWay = this.cashierVm.otherPayWayList.FirstOrDefault();
            #endregion
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (cashierVm == null)
                return;
            //Init();
        }

        private void UserControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {

        }
    }
}
